package com.fgs.common.utils;

import android.text.TextUtils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author fgs
 * @date 2020/3/27
 **/

public class DateUtil {
    /**
     * 字符串转换到时间格式
     *
     * @param dateStr   需要转换的字符串
     * @param formatStr 需要格式的目标字符串 举例 yyyy-MM-dd
     * @return Date 返回转换后的时间
     * @throws ParseException 转换异常
     */
    public static Date stringToDate(String dateStr, String formatStr) {
        DateFormat sdf = new SimpleDateFormat(formatStr);
        Date date = null;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }


    /**
     * 把整型时间转化为字符串格式yyyy-MM-dd HH:mm:ss
     *
     * @param timestamp
     * @param format    格式yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String getStandardTime(long timestamp, String format) {

        try {
            if (timestamp > 0) {
                SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault());
                Date date = new Date(timestamp);
                return formatter.format(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return "";
    }

    /**
     * 把整型时间转化为字符串格式MM-dd HH:mm
     *
     * @param timestamp
     * @return
     */
    public static String getStringTimeOfLong(long timestamp) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
            Date date = new Date(timestamp * 1000);
            sdf.format(date);
            return sdf.format(date);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 比较时间大小
     *
     * @param begin
     * @param end
     * @return 0 相等 1 开始时间小于结束时间 -1 开始时间大于结束时间
     */
    public static int compareDate(String begin, String end) {
        return compareDate(begin, end, "yyyy-MM-dd");
    }


    /**
     * 比较时间大小
     *
     * @param begin
     * @param end
     * @return 0 相等 1 开始时间小于结束时间 -1 开始时间大于结束时间
     */
    public static int compareDate(String begin, String end, String format) {
        DateFormat df = new SimpleDateFormat(format);
        try {
            Date beginDate = df.parse(begin);
            Date endDate = df.parse(end);
            if (beginDate.getTime() < endDate.getTime()) {
                return 1;
            } else if (beginDate.getTime() > endDate.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取现在是周几
     */
    public static int getDayOfWeek() {
        Calendar calendar = Calendar.getInstance();
        int todayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        return todayOfWeek;
    }

    /**
     * 获取现在N天后是周几
     */
    public static int getDayOfWeek(int n) {
        int afterNDay = (getDayOfWeek() + n) % 7;
        return afterNDay;
    }

    /**
     * 日期补零
     */
    public static String addZero(int n) {
        if (n < 10) {
            return "0" + n;
        }
        return n + "";
    }


    // date要转换的date类型的时间
    public static long dateToLong(Date date) {
//        return date.getTime() / 1000;
        return date.getTime();
    }

    /**
     * 获取今天以后的日期yyyy-MM-dd
     *
     * @return
     */
    public static String getTodayDate(String format, int day) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        Calendar calendar = Calendar.getInstance();
        calendar.roll(Calendar.DAY_OF_YEAR, +day);
        return df.format(calendar.getTime());
    }

    /**
     * 获取今天以后的日期yyyy-MM-dd
     *
     * @return
     */
    public static String getTodayDate(int day) {
        return getTodayDate("yyyy-MM-dd", day);
    }

    /**
     * 获取今天的日期yyyy-MM-dd
     *
     * @return
     */
    public static String getTodayDate() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        return df.format(calendar.getTime());
    }

    /**
     * 获取明天的日期yyyy-MM-dd
     *
     * @return
     */
    public static String getTomorrowDate() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.roll(Calendar.DAY_OF_YEAR, +1);
        return df.format(calendar.getTime());
    }

    /**
     * 获取明天的日期yyyy-MM-dd
     *
     * @return
     */
    public static String getTomorrowDate(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        Calendar calendar = Calendar.getInstance();
        calendar.roll(Calendar.DAY_OF_YEAR, +1);
        return df.format(calendar.getTime());
    }

    /**
     * 获取后天的日期yyyy-MM-dd
     *
     * @return
     */
    public static String getTheAfterDayDate() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.roll(Calendar.DAY_OF_YEAR, 2);
        return df.format(calendar.getTime());
    }

    /**
     * 字符串转化指定日期格式
     *
     * @param time
     * @return
     */
    public static String getDateStringFormat(String time, String returnFormat) {
        String s = "";
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date;
            date = format.parse(time);
            SimpleDateFormat format1 = new SimpleDateFormat(returnFormat);
            s = format1.format(date);
        } catch (Exception e) {
            return "";
        }

        return s;
    }

    /**
     * 字符串转化指定日期格式
     *
     * @param time
     * @return
     */
    public static String getDateStringFormat(String time, String initialFormat, String returnFormat) {
        String s = "";
        try {
            SimpleDateFormat format = new SimpleDateFormat(initialFormat);
            Date date;
            format.setLenient(false);
            date = format.parse(time);
            SimpleDateFormat format1 = new SimpleDateFormat(returnFormat);
            format1.setLenient(false);
            s = format1.format(date);
        } catch (Exception e) {
            return "";
        }

        return s;
    }


    /**
     * String 转long 转 Format
     *
     * @param time
     * @param stringFormat
     * @return
     */
    public static String getFormatDate(String time, String stringFormat) {
        if (TextUtils.isEmpty(time)) return "";
        try {
            return DateUtil.getStandardTime(Long.parseLong(time), stringFormat);
        } catch (Exception e) {

            return "";
        }
    }

    //当前月第一天
    public static String getFirstDayOfCurrentMonth() {
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        Date date = calendar.getTime();
        String firstDate = dateFormat2.format(date);
        return firstDate;
    }
    //当前月最后一天
    public static String getLastDayOfCurrentMonth() {
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date date = calendar.getTime();
        String lastDate = dateFormat2.format(date);
        return lastDate;
    }
    //指定年月最后一天
    public static String getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));
        return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
    }

    //指定年月第一天
    public static String getFirstDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
        return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
    }

    // strTime要转换的String类型的时间
    // formatType时间格式
    // strTime的时间格式和formatType的时间格式必须相同
    public static long stringToLong(String strTime, String formatType) {
        try {
            Date date = stringToDate(strTime, formatType); // String类型转成date类型
            if (date == null) {
                return 0;
            } else {
                long currentTime = dateToLong(date); // date类型转成long类型
                return currentTime;
            }
        } catch (Exception e) {

        }
        return 0;

    }

    /**
     * 时长格式处理
     *
     * @param time 时长
     * @param type 时长单位 0 天 1 小时
     * @return
     */
    public static String durationFormat(long time, int type) {
        float length = 0;
        int day = (int) (time / (1000 * 60 * 60 * 24));
        int hour = (int) (time / (1000 * 60 * 60) - day * 24);
        int min = (int) ((time / (60 * 1000)) - day * 24 * 60 - hour * 60);
        int mSecond = (int) ((time / 1000) - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        if (type == 0) {//单位：天

            if (day > 0) {
                length = day;
            }
            if (hour > 0) {
                length += ((float) hour / 24);
            }

            return CommonUtil.keepTwoDecimal(length + "");
        } else if (type == 1) {//单位：小时
            if (day > 0) {
                length = day * 24;
            }
            if (hour > 0) {
                length += hour;
            }
            if (min > 0) {
                length += (float) min / 60;
            }
            return CommonUtil.keepTwoDecimal(length + "");
        }

        return "";
    }


    /**
     * 根据毫秒时间戳来格式化字符串
     * 今天显示几时几分、昨天显示昨天、前天显示前天.
     * 早于前天的显示具体年-月-日，如2017-06-12；
     *
     * @param timeStamp 毫秒值
     * @return 几时几分 昨天 前天 或者 yyyy-MM-dd 类型字符串
     */
    public static String format(long timeStamp) {
        String strTime = "";
        long curTimeMillis = System.currentTimeMillis();
        Date curDate = new Date(curTimeMillis);
        int todayHoursSeconds = curDate.getHours() * 60 * 60;
        int todayMinutesSeconds = curDate.getMinutes() * 60;
        int todaySeconds = curDate.getSeconds();
        int todayMillis = (todayHoursSeconds + todayMinutesSeconds + todaySeconds) * 1000;
        long todayStartMillis = curTimeMillis - todayMillis;
        if (timeStamp >= todayStartMillis) {
            Date date = new Date(timeStamp);
            strTime = addZero(date.getHours()) + ":" + addZero(date.getMinutes());//显示几时几分
            return strTime;
        }
        int oneDayMillis = 24 * 60 * 60 * 1000;
        long yesterdayStartMillis = todayStartMillis - oneDayMillis;
        if (timeStamp >= yesterdayStartMillis) {
            return "昨天";
        }
        long yesterdayBeforeStartMillis = yesterdayStartMillis - oneDayMillis;
        if (timeStamp >= yesterdayBeforeStartMillis) {
            return "前天";
        }
//        strTime = getStandardTime(timeStamp, "yyyy-MM-dd ");
        strTime = getStandardTime(timeStamp, "MM-dd");
        return strTime;
    }

    /**
     * 根据时间戳来判断当前的时间是几天前,几分钟,刚刚
     *
     * @param long_time
     * @return
     */
    public static String getTimeStateNew(String long_time) {
        String long_by_13 = "1000000000000";
        String long_by_10 = "1000000000";
        if (Long.valueOf(long_time) / Long.valueOf(long_by_13) < 1) {
            if (Long.valueOf(long_time) / Long.valueOf(long_by_10) >= 1) {
                long_time = long_time + "000";
            }
        }
        Timestamp time = new Timestamp(Long.valueOf(long_time));
        Timestamp now = new Timestamp(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("MM-dd");
//    System.out.println("传递过来的时间:"+format.format(time));
//    System.out.println("现在的时间:"+format.format(now));
        long day_conver = 1000 * 60 * 60 * 24;
        long hour_conver = 1000 * 60 * 60;
        long min_conver = 1000 * 60;
        long time_conver = now.getTime() - time.getTime();
        long temp_conver;
//    System.out.println("天数:"+time_conver/day_conver);
        if ((time_conver / day_conver) < 3) {
            temp_conver = time_conver / day_conver;
            if (temp_conver <= 2 && temp_conver >= 1) {
                return temp_conver + "天前";
            } else {
                temp_conver = (time_conver / hour_conver);
                if (temp_conver >= 1) {
                    return temp_conver + "小时前";
                } else {
                    temp_conver = (time_conver / min_conver);
                    if (temp_conver >= 1) {
                        return temp_conver + "分钟前";
                    } else {
                        return "刚刚";
                    }
                }
            }
        } else {
            return format.format(time);
        }
    }

    public static String getStringByFormat(Date date, String format) {
        SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
        String strDate = null;
        try {
            strDate = mSimpleDateFormat.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strDate;
    }


    public static String getFirstDayAndLastDayOfMonth(int num) {
        StringBuffer stringBuffer = new StringBuffer();
        SimpleDateFormat dateFormater = new SimpleDateFormat(
                "yyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, num);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.getTime();
        stringBuffer.append(dateFormater.format(cal.getTime()) + "");
        cal.set(Calendar.DAY_OF_MONTH,
                cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        stringBuffer.append("," + dateFormater.format(cal.getTime()));
        return stringBuffer.toString();

    }

    /**
     * 每个月第一天
     *
     * @param diff
     * @return
     */
    public static String getMonthFirstDay(int diff) {
        StringBuffer stringBuffer = new StringBuffer();
        SimpleDateFormat dateFormater = new SimpleDateFormat(
                "yyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, diff);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.getTime();
        stringBuffer.append(dateFormater.format(cal.getTime()) + "");
        return stringBuffer.toString();

    }

    /**
     * 每个月最后一天
     *
     * @param diff
     * @return
     */
    public static String getMonthLastDay(int diff) {
        StringBuffer stringBuffer = new StringBuffer();
        SimpleDateFormat dateFormater = new SimpleDateFormat(
                "yyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, diff);
        cal.set(Calendar.DAY_OF_MONTH,
                cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        stringBuffer.append(dateFormater.format(cal.getTime()));
        return stringBuffer.toString();

    }

    //字符串 日期格式 转换
    public static String validDateFormat(String time, String originalFormat) {
        try {
            if (!TextUtils.isEmpty(time)) {
                if (time.contains("长期")) {
                    return "2099-12-31";
                }

                String number = getNumbers(time);
                if (CheckUtil.isDate(number)) {
                    return getDateStringFormat(number, "yyyyMMdd", "yyyy-MM-dd");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    //字符串 日期格式 转换驾驶证长期换
    public static String validDateFormatChangQi(String shengXiaoTime,String time,
                                                String originalFormat,String birthDay) {
        try {
            //长期的
            if (!TextUtils.isEmpty(time)) {
                if (time.contains("长期")) {
                    try {

                        String[] shengXiaoSplit = shengXiaoTime.split("-");
//                        String[] daoQiSplit = time.split("-");
                        String[] split = getYear().split("-");
                        int todayYear = Integer.valueOf(split[0]) ;
                        int birth = Integer.valueOf(birthDay) ;
                        int age = todayYear - birth;
                        if (60<age) {
                            int nextYear = todayYear + 1;
                            String newYearString = nextYear +"-"+ split[1] +"-"+ split[2];
                            return newYearString;
                        }else {
                            int cha = 60 - age;
                            int shengXiaoYear = Integer.valueOf(shengXiaoSplit[0]) ;
                            int daQiYear=shengXiaoYear+cha;
                            String newYearString = daQiYear +"-"+ shengXiaoSplit[1] +"-"+ shengXiaoSplit[2];
                            return newYearString;
                        }

                    }catch (Exception e){
                        return "2099-12-31";
                    }

                }

                String number = getNumbers(time);
                if (CheckUtil.isDate(number)) {
                    return getDateStringFormat(number, "yyyyMMdd", "yyyy-MM-dd");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getYear(){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+08")); //设置时区
        Date curDate = new Date(System.currentTimeMillis()); //获取当前时间
        String createDate = formatter.format(curDate);   //格式转换

        return createDate;
    }

    public static   String getTimeNow(){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置时间格式
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+08")); //设置时区
        Date curDate = new Date(System.currentTimeMillis()); //获取当前时间
        String createDate = formatter.format(curDate);   //格式转换

        return createDate;
    }



    //提取数字
    public static String getNumbers(String content) {
        if (!TextUtils.isEmpty(content)) {
            String regEx = "[^0-9]";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(content);
            return m.replaceAll("").trim();
        }
        return "";
    }


    public static String getTime(){
        long time=System.currentTimeMillis();//获取系统时间的13位的时间戳
        String  str=String.valueOf(time);
        return str;
    }

    public static boolean isToday(long timestamp) {
        Date date = new Date(timestamp);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String datestr = sdf.format(date);
        String todayStr = sdf.format(new Date());
        return datestr.equals(todayStr);
    }


    public static int isChaHors(long timestamp) {
        long time=System.currentTimeMillis();
        long timeDifference =time - timestamp;
        int hours =(int)(timeDifference /(60*60 *1080));

        return hours;
    }

}
